package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.FollowBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.mapper.ApBehaviorEntryMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP行为实体表,一个行为实体可能是用户或者设备，或者其它 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2021-05-29
 */
@Service
public class ApBehaviorEntryServiceImpl extends ServiceImpl<ApBehaviorEntryMapper, ApBehaviorEntry> implements IApBehaviorEntryService {

    @Override
    public ApBehaviorEntry getEntry(EntryDto dto) {
        //判断参数
        if (dto == null || dto.getUserId() == null && StringUtils.isEmpty(dto.getEquipmentId())) {
            return null;
        }

        //如果userId不为空
        if (dto.getUserId() != null) {
            //查询
            LambdaQueryWrapper<ApBehaviorEntry> query = new LambdaQueryWrapper<>();
            query.eq(ApBehaviorEntry::getEntryId, dto.getUserId().toString());
            query.eq(ApBehaviorEntry::getType, 1);
            ApBehaviorEntry entry = this.getOne(query);
            if (entry != null) {
                return entry;
            } else {
                ApBehaviorEntry behaviorEntry = new ApBehaviorEntry();
                behaviorEntry.setType(1);
                behaviorEntry.setEntryId(dto.getUserId().toString());
                behaviorEntry.setCreatedTime(new Date());
                this.save(behaviorEntry);
                return behaviorEntry;
            }
        }
        if (dto.getEquipmentId() != null) {
            LambdaQueryWrapper<ApBehaviorEntry> query = new LambdaQueryWrapper<>();
            query.eq(ApBehaviorEntry::getEntryId, dto.getEquipmentId());
            query.eq(ApBehaviorEntry::getType, 0);
            ApBehaviorEntry entry = this.getOne(query);
            if (entry != null) {
                return entry;
            } else {
                ApBehaviorEntry behaviorEntry = new ApBehaviorEntry();
                behaviorEntry.setType(0);
                behaviorEntry.setEntryId(dto.getEquipmentId());
                behaviorEntry.setCreatedTime(new Date());
                this.save(behaviorEntry);
                return behaviorEntry;
            }
        }
        return null;
    }
}
